<?php

namespace App\Models\System;

use App\Components\Redis;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class SystemRoleUser extends Model
{
    use SoftDeletes;

    protected $table = 'system_role_user';

    public static function userRole(int $userId): array
    {
        $cacheKey = 'MODELS:SYSTEM:SYSTEMROLEUSER:USERROLE:' . $userId;
        $cacheRs = Redis::get($cacheKey);
        if ($cacheRs !== false && $cacheRs !== null) {
            return json_decode($cacheRs, true);
        }

        $roleRs = SystemRoleUser::select('id', 'role_id')
            ->where('user_id', $userId)
            ->orderBy('id', 'asc')->get()->toArray();
        $roleRs = array_column($roleRs, 'role_id');

        Redis::setex($cacheKey, Redis::mediumTime(), json_encode($roleRs));
        return $roleRs;
    }

    public static function clearUserRoleCache(int $userId): bool
    {
        $cacheKey = 'MODELS:SYSTEM:SYSTEMROLEUSER:USERROLE:' . $userId;
        Redis::del($cacheKey);
        return true;
    }
}
